<template>
    <div class="changeImage" >
        <div class="uploadArea">
            <el-upload
              action="#"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :on-change="handleChange"
              :limit="1"
              list-type="picture-card"
              :auto-upload="false"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
            <div class="prompt">
                <i class="iconfont icon-tishi" ></i>
                <span>请选择文件大小小于2M的jpg或png文件</span>
            </div>
          </div>
          <button  class="uploadImage" @click="uploadHead">上传头像</button>
    </div>
  </template>
  
  <script>
  import { uploadHeadImage } from "@/api/all";
  import { Loading, Message } from "element-ui";
  import { mapState, mapMutations } from "vuex";
  export default {
  data(){
    return {
        dialogImageUrl: "",
        dialogVisible: false,
        disabled: false,
        fileList: [],
    }
  },
  computed:{
        ...mapState('login',['username','image']),
        ...mapState('app',['loading']),
    },
  methods:{
    ...mapMutations("login", [
      "SET_IMAGE",
    ]),
    ...mapMutations("app", [
      "setLoading","setTitle"
    ]),
     //删除上传的图片
     handleRemove(file) {
      this.fileList = [];
    },
    //要求只能上传一张图片
    handleExceed(files, fileList) {
      Message.error('只能上传一张图片，请删除文件后重新上传');
    },
    //进行图片放大显示
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
     //规定上传文件格式要求，把上传的图片存入数组
     handleChange(file, fileList) {
      if (!(file.raw.type === 'image/jpeg' || file.raw.type === 'image/png')){
        Message.error('只能上传 JPG/PNG 格式的图片！');
        console.log(file.raw.type)
        return false
      }
      else this.fileList = fileList;
    },
    uploadHead(){
      if(this.fileList.length==0)
      Message.error("请先选择要上传的头像！")
    else{
      this.setLoading(true);
      this.setTitle("头像上传中")
      this.confirmUpload();
    }
    },
    async confirmUpload() {
      const formData = new FormData();
      const file = this.fileList[0].raw;
      formData.append("file", file);
      if(this.image=="") formData.append('image',"null");
      else  formData.append('image', this.image);
      formData.append('username', this.username);
      await uploadHeadImage(formData)
        .then((res) => {
          if (res.data.code === 200) {
              Message.success("头像上传成功");
              this.SET_IMAGE(res.data.data.fileUrl)
              this.setLoading(false);
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },
  }
  }
  </script>
  
  <style scoped>
  .changeImage{
    height: 70vh;
    width:90%;
    background: #F7F8F8;
    margin: 0px auto ;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .uploadArea{
    display: flex;
    width:800px;
    height:180px;
    line-height:180px;
    margin-left: 80px;
    /* justify-content: center; */
    margin-top: 50px;
  }
  .uploadImage{
    background: rgba(42, 81, 77, 1);
    color: #fff;
    width: 140px;
    height: 40px;
    border-radius: 4px;
    border: 1px solid #215c3d;
    transition: all 0.3s;
    margin-left: 80px;
}
.uploadImage:hover {
    cursor: pointer;
    background: rgba(42, 81, 77, 0.9);
}
.prompt{
    width: 320px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    background:  rgba(54, 105, 100, 0.3);
    border-radius: 8px;
    color: #474646;
    margin-left: 50px;
    font-size: 14px;
}
  </style>